package cn.chinaiptv.serverlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import cn.chinaiptv.bean.PlatformParamsBean;
import cn.chinaiptv.bean.RecordBean;
import cn.chinaiptv.utils.GenerateWorkSheet;
import cn.chinaiptv.utils.ParamsFromConfFile;
import cn.chinaiptv.utils.PlatformParamUtils;
import cn.chinaiptv.utils.RecordUtils;
import cn.chinaiptv.utils.UUID32;

/**
 * Servlet implementation class RequestServlet
 */

public class DeleteServlet extends HttpServlet {
	private String actionType = "DELETE";
	// 删除类型，
	private String DELETETYPE = DELETE_FILE;
	// 删除根目录或者文件夹，
	private static final String DELETE_FILE = "0";
	// 更新单个文件
	private static final String DELETE_TAR = "1";
	// 是否需要解压 1.需要解压，0 无需解压
	private int UnTar = NEEDUNTAR;
	// 需要解压
	private static final int NEEDUNTAR = 1;
	// 不需要解压
	private static final int UNNEEDUNTAR = 0;
	private ArrayList<PlatformParamsBean> platformParamsBeans = new ArrayList<PlatformParamsBean>();
	private String tarname = "";
	private String destpath = "";
	private String group = "";
	private String destfile = "";
	private String crtid = "";
	private String platform = "";
	private String operation = "filedelete";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public DeleteServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=UTF-8");
		// log日志
		Logger logger = Logger.getLogger(DeleteServlet.class);
		PrintWriter out = response.getWriter();
		// destpath = request.getParameter("destpath");
		group = request.getParameter("group");
		platform = request.getParameter("platform");
		DELETETYPE = request.getParameter("operationVal");
		if (DELETETYPE.equals(DELETE_FILE)) { // 删除文件
			destfile = request.getParameter("filetoDelete");
			destpath = request.getParameter("fileDestpath");
			UnTar = UNNEEDUNTAR;
		} else if (DELETETYPE.equals(DELETE_TAR)) { // 删除再等个tar
			destpath = request.getParameter("fileDestpath");
			destfile = "";
			UnTar = UNNEEDUNTAR;// 需要解压
		}
		crtid = UUID32.genUUID32();
		HashMap<String, PlatformParamsBean> platforms = PlatformParamUtils
				.getplatform("param.xml");
		PlatformParamsBean platformParamsBean = platforms.get(platform);
		String cspid = platformParamsBean.getCspid();
		String lspid = platformParamsBean.getLspid();
		// // 获取tar包，生成指令文件
		logger.info("*****平台发送更新请求开始*******");
		// 模板同步命令请求
		if (platform.equals("zte")) {
			//group = "frame1018";
			System.out.println(destfile + "====" + destpath + "===" + group);
			tarname = ParamsFromConfFile.default_tar() + ".tar"; // 中兴tar
			System.out.println(tarname + "===" + destfile + "+++" + destpath
					+ "===" + UnTar);
			GenerateWorkSheet generateWorkSheet = new GenerateWorkSheet();
			try {
				String fileUrl = generateWorkSheet.generateXML(tarname,
						destfile, "zte_workorder",
						ParamsFromConfFile.setFileSetId(),
						ParamsFromConfFile.setFileId(), actionType, group,
						UnTar + "", destpath);
				sendRequest(platform, response, crtid, cspid, lspid, logger,
						fileUrl, group, operation, destfile);
			} catch (Exception e) {
				logger.info("[请求消息]：相关性标识：" + crtid + " 生成工单文件失败");
			}

		} else {
			//group = "aishangtest";
			System.out.println(destfile + "====" + destpath + "===" + group);
			tarname = group + ".zip"; // 华为zip
			System.out.println(tarname + "===" + destfile + "+++" + destpath
					+ "===" + UnTar);
			GenerateWorkSheet generateWorkSheet = new GenerateWorkSheet();
			try {
				String fileUrl = generateWorkSheet.generateXML(tarname,
						destfile, "hua_workorder",
						ParamsFromConfFile.setFileSetId(),
						ParamsFromConfFile.setFileId(), actionType, group,
						UnTar + "", destpath);
				sendRequest(platform, response, crtid, cspid, lspid, logger,
						fileUrl, group, operation, destfile);
			} catch (Exception e) {
				logger.info("[请求消息]：相关性标识：" + crtid + " 生成工单文件失败");
			}

		}

		logger.info("*****平台发送更新请求结束*******");

	}

	/**
	 * 发送请求，并进行相关日志信息的记录
	 * 
	 * @param response
	 * @param crtid
	 * @param cspid
	 * @param lspid
	 * @param logger
	 * @param fileUrl
	 * @throws RemoteException
	 * @throws IOException
	 */
	private void sendRequest(String message, HttpServletResponse response,
			String crtid, String cspid, String lspid, Logger logger,
			String fileUrl, String group, String operation, String destFile)
			throws RemoteException, IOException {
		logger.info("请求参数信息：CSPID：" + cspid + "====LSPID:" + lspid
				+ "====相关性标识：" + crtid + "=====指令文件地址：" + fileUrl);
		if (message.equals("zte")) {
			cn.chinaiptv.zte.client.CSPResult cspResult = new cn.chinaiptv.zte.client.CSPRequestProxy()
					.templateSyncCmdRequest(cspid, lspid, crtid, fileUrl);
			// 获取同步命令请求后的结果
			int res = cspResult.getResult();
			String errorDescription = cspResult.getErrorDescription();
			PrintWriter out = response.getWriter();
			String status = "";
			if (res == 0) {
				logger.info("[请求消息]：相关性标识：" + crtid + " 请求成功");
				out.write("请求成功");
				String resutlJson = "{" + "\"success\":" + "true" + "}";
				out.print(resutlJson);
				status = "请求成功";
			} else if (res == -1) {
				logger.info("[请求消息]：相关性标识：" + crtid + " 请求失败，失败描述信息："
						+ errorDescription);
				out.write(" 请求失败，失败描述信息：" + errorDescription);
				String resutlJson = "{" + "\"success\":" + "false" + "}";
				out.print(resutlJson);
				status = "请求失败";
			}
			SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd");
			String timeStr = dateFormater.format(new Date());
			RecordBean bean = new RecordBean(timeStr, message, group,
					operation, destFile, fileUrl, status);
			RecordUtils.writeRecord(bean);
		} else {
			cn.chinaiptv.zte.client.CSPResult cspResult = new cn.chinaiptv.zte.client.CSPRequestProxy()
			.templateSyncCmdRequest(cspid, lspid, crtid, fileUrl);
			// 获取同步命令请求后的结果
			int res = cspResult.getResult();
			String errorDescription = cspResult.getErrorDescription();
			PrintWriter out = response.getWriter();
			String status = "";
			if (res == 0) {
				logger.info("[请求消息]：相关性标识：" + crtid + " 请求成功");
				out.write("请求成功");
				String resutlJson = "{" + "\"success\":" + "true" + "}";
				out.print(resutlJson);
				status = "请求成功";
			} else if (res == -1) {
				logger.info("[请求消息]：相关性标识：" + crtid + " 请求失败，失败描述信息："
				+ errorDescription);
				out.write(" 请求失败，失败描述信息：" + errorDescription);
				String resutlJson = "{" + "\"success\":" + "false" + "}";
				out.print(resutlJson);
				status = "请求失败";
			}
			SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd");
			String timeStr = dateFormater.format(new Date());
			RecordBean bean = new RecordBean(timeStr, message, group,
			operation, destFile, fileUrl, status);
			RecordUtils.writeRecord(bean);
			
			/*
			cn.chinaiptv.hua.client.CSPResult huaCspRes = new cn.chinaiptv.hua.client.CSPRequestProxy()
					.execCmd(cspid, lspid, crtid, fileUrl);
			// 获取同步命令请求后的结果
			int res = huaCspRes.getResult();
			String errorDescription = huaCspRes.getErrorDescription();
			PrintWriter out = response.getWriter();
			if (res == 0) {
				logger.info("[请求消息]：相关性标识：" + crtid + " 请求成功");
				out.write("请求成功");
			} else if (res == -1) {
				logger.info("[请求消息]：相关性标识：" + crtid + " 请求失败，失败描述信息："
						+ errorDescription);
				out.write(" 请求失败，失败描述信息：" + errorDescription);
			}
			*/
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}
